<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<%@ include file="/WEB-INF/jsp/common/header.jsp" %>
<script type="text/javascript" src="${root}/easyui/jeasyui-extensions/jquery.euploadify.js"></script>
<script type="text/javascript" src="${root}/easyui/plugins/uploadify/jquery.uploadify.js"></script>
<link type="text/css" rel="stylesheet" href="${root}/easyui/plugins/uploadify/uploadify.css">
<style>
	table { float:left; margin-right: 20px;}
	.row {position:relative;  float:left; width:100px; margin:3px; }
	.row span{position: absolute; top: 6px; left: 6px; cursor: pointer;color:red;}
	.row img{ width:100%; border: 1px solid gray;  }
</style>
</head>
<body>

<!-- ===========================  商品新增  对话框  ========================================= -->
	<div id="addProductDialog" title="添加商品" class="easyui-dialog" data-options="modal:true,closed:true" style="width:700px;height:500px;">
		<form id="addProductForm" action="${root}/admin/product/save" method="post">
		<div>
			<table>
				<tr>
					<td>商品名称</td><td><input type="text" name="name" class="easyui-validatebox" data-options="required:true"/></td>
				</tr>
				<tr>
					<td>商品价格</td><td><input type="text" name="price" class="easyui-numberbox"  id="addNumberbox" data-options="required:true"/></td>
				</tr>
				<tr>
					<td>商品毛重</td><td><input type="text" name="weight" class="easyui-validatebox" data-options="required:true"/></td>
				</tr>
				<tr>
					<td>商品状态</td><td>下架<input type="radio" name="onsale" value="false" checked/>
										上架<input type="radio" name="onsale" value="true"/>
					</td>
				</tr>
				<tr>
					<td>上架时间</td><td><input type="text" name="onsaleDate" class="easyui-my97"/></td>
				</tr>
				<tr>
					<td>库存</td><td><input type="text" name="store" class="easyui-numberbox" data-options="required:true"/></td>
				</tr>
				<tr>
					<td>详情页</td><td><input type="text" name="detail" class="easyui-validatebox" data-options="required:true"/></td>
				</tr>
				<tr>
					<td>商品类别</td><td><input type="text" name="category_id" id="categoryCombo" data-options="required:true"/></td>
				</tr>
				
			</table>
			<table>
				<tbody id="attrs"></tbody>
			</table>
		</div>
		<br style="clear: both;"/>
		<div>
			<input id="addUpload" type="text"/>
		</div>
		<div id="addImages"></div>
		</form>
	</div>
	
	
<!-- ===========================  商品修改  对话框  ========================================= -->
	 <div id="updateProductDialog" title="修改商品" class="easyui-dialog" data-options="modal:true,closed:true" style="width:700px;height:500px;">
		<form id="updateProductForm" action="${root}/admin/product/update" method="post">
		<div>
			<table>
				<tr>
					<td>商品ID</td><td><input type="text" name="id" class="easyui-validatebox" data-options="required:true" readonly="readonly" /></td>
				</tr>
				<tr>
					<td>商品名称</td><td><input type="text" name="name" class="easyui-validatebox" data-options="required:true"/></td>
				</tr>
				<tr>
					<td>商品价格</td><td><input type="text" name="price" class="easyui-numberbox"  id="updateNumberbox" data-options="required:true"/></td>
				</tr>
				<tr>
					<td>商品毛重</td><td><input type="text" name="weight" class="easyui-validatebox" data-options="required:true"/></td>
				</tr>
				<tr>
					<td>商品状态</td><td>下架<input type="radio" name="onsale" value="false" checked/>
										上架<input type="radio" name="onsale" value="true"/>
					</td>
				</tr>
				<tr>
					<td>上架时间</td><td><input type="text" name="onsaleDate" class="easyui-my97"/></td>
				</tr>
				<tr>
					<td>库存</td><td><input type="text" name="store" class="easyui-numberbox" data-options="required:true"/></td>
				</tr>
				<tr>
					<td>详情页</td><td><input type="text" name="detail" class="easyui-validatebox" data-options="required:true"/></td>
				</tr>
				<tr>
					<td>商品类别</td><td><input type="text" name="category_id"  id="updateCategoryCombo" data-options="required:true"/></td>
				</tr>
				
			</table>
			<table>
				<tbody id="updateAttrs"></tbody>
			</table>
		</div>
		<br style="clear: both;"/>
		<div>
			<input id="updateUpload" type="text"/>
		</div> 
		<div id="updateImages" ></div>
		</form>
	</div> 

	
	
	
	
	<!-- ===========================  商品  工具条  ========================================= -->
	<div id="productToolbar">
		<a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-add'" id="addBtn">新增</a>
		<a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-remove'" id="deleteBtn">删除</a>
		<a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-edit'" id="updateBtn">修改</a>
	</div>
	<!-- ===========================  商品 列表  ========================================= -->
	<table id="productTable"></table>
	
<script type="text/javascript">

//  ==================  商品  删除   =============================
	$("#deleteBtn").click(function(){
		var row = $("#productTable").datagrid('getSelected');
		if(row){
			$.messager.confirm("确定删除该商品吗？",function(r){
				if(r){
					$.get("${root}/admin/product/delete",{ product_id:row.id },function(){
						$("#productTable").datagrid("reload");
					});
				}
			
			});
			
		}else{
			$.messager.alert("请选择要删除的行");
			return;
		}
	});


//  ==================  商品 修改   =============================
	// 初始化dialog
	$("#updateProductDialog").dialog({
		buttons:[
			{ text:"保存",handler:function(){
				$("#updateProductForm").form("submit",{
					url:"${root}/admin/product/update",
					onsubmit: function(){
						return $("#updateProductForm").form("validate");
					},
					success: function(){
						$("#updateProductDialog").dialog("close");
						$("#productTable").datagrid("reload");
					}
				
				});
				}
			}
		]
	});
	// 点击修改按钮
	$("#updateBtn").click(function(){
		var row = $("#productTable").datagrid('getSelected');
		if(row){
			$("#updateProductForm").form("load", {id:row.id,name:row.name,price:row.price,weight:row.weight,onsale:row.onsale,onsaleDate:row.onsaleDate,store:row.store,detail:row.detail,category_id:row.category_id});
			$("#updateProductDialog").dialog("open");
			
		}else{
			$.messager.alert("请选择要修改的行");
			return;
		}
	});
	$("#updateNumberbox").numberbox({
		precision:2
	});
	
	$("#updateUpload").euploadify({
 		width: 580,
        //height: 400,
        multi: true,
        multiTemplate: 'simple',
        auto: false,
        removeCompleted: true,// 移除已经上传的图片
        swf: '${root}/easyui/plugins/uploadify/uploadify.swf',
        uploader: '${root}/upload',
        onUploadSuccess: function(file, data){
        	var $updateImages = $("#updateImages");
        	// uploadify 返回的是json字符串，需要手动转换为json对象
        	var json = JSON.parse(data);
        	var md5 = json.filename.replace(/\..*/,"");
        	// 动态生成图片对应的文本框，文本框中包含图片名
        	// 生成图片预览，生成image标签
        	if($("img[src*="+md5+"]").length == 0) {
        		var html = "<div class='row'><img src='${root}/image/"+json.filename+"'/><input type='hidden' name='images' value='"+json.filename+"'/><span>移除</span></div>";
        		$updateImages.append($(html));
        	}	        	
        }
 	});
	
	//　商品  修改 时的combotree
	$("#updateCategoryCombo").combotree({
	//var row = $("#productTable").datagrid('getSelected');
		url:"${root}/admin/attr/findAll",
		dataPlain: true,
		textField: "text",
		valueField: "id",
		//value:
		 onSelect: function(record){
			var row = $("#productTable").datagrid('getSelected');
			$.get("${root}/admin/attr/findByCategoryFetch", {cid:record.id},function(json){
				var $attrs = $("#updateAttrs").empty();
				for(var i = 0; i < json.rows.length; i++) {
				var html = "<tr><td>"+json.rows[i].name+"</td><td><input type='hidden' name='attr_names' value='"+json.rows[i].name+"'/><input type='text' class='attrCombo' name='values'></td></tr>";
					//var html = "<tr><td>"+json.rows[i].attr_name+"</td><td><input type='hidden' name='attr_name' value='"+json.rows[i].attr_name+"'/><input type='text' class='attrCombo' name='value'></td></tr>";
					$(html).appendTo($attrs);
				}
				
				var combos = $attrs.find(".attrCombo");
				for(var i = 0; i < json.rows.length; i++) {
					$(combos[i]).combobox({
					    name: json.rows[i].name,//自定义属性（存放属性名）
						textField: "name",
						valueField: "name",
						required: true,
						data: json.rows[i].attrValues
					});
				}
				// 查询商品的 属性名及对应的属性值
				$.get("${root}/admin/product/findProductAll", {product_id:row.id}, function(json){
					var map = {};
					for(var i = 0; i < json.length; i++){
						map[json[i].attr_name] = json[i].value;// map[key] = value;
					}
					// key    value
					// 品牌        ONLY
					
					var combos = $attrs.find(".attrCombo");
					for(var i = 0; i < combos.length; i++) {
						var value = map[$(combos[i]).combobox("options").name]; // 通过key拿到value
						$(combos[i]).combobox("select", value);
					}
				});
				
				//console.log("---图片修改时---");
				//console.log(row.id);
				// 修改时 显示图片
				$.get("${root}/admin/product/findProductImage",{product_id:row.id}, function(json){
					//console.log(json[0]);
					// (多件商品共用这些个image标签)清空已显示的image标签
					$("#updateImages").empty();
					var $updateImages = $("#updateImages"); 
					
					for(var i =0; i<json.length; i++){
						var html = "<div class='row'><img src='${root}/image/"+json[i].url+"'/><input type='hidden' name='images' value='"+json[i].url+"'/><span>移除</span></div>";
        				$updateImages.append($(html));
					}
					
					
				});
				
				$("#updateImages").on("click", "span", function(){
					$(this).parent().remove();
				});
				
				
				
				/*$(".attrCombo").combobox({
					onLoadSuccess: function(){
					$.get("${root}/admin/product/findProductAll", {product_id:row.id}, function(json){
						console.log(json.rows.length);
						console.log("=");
						//console.log(json.rows[0]);
						var v = json;
						console.log(v.rows);
						//console.log(v.rows[0]);
						console.log("=== combobox ===");
						
						for(var i = 0; i<v.rows.length; i++){
							console.log("==========");
							console.log(v.rows[i]);
						}
						
						console.log(" = = ");
						console.log(json.rows[0]);
						for(var j = 0; j<json.rows.length; j++ ){}
						var c = $(".attrCombo").combobox('getData');
						
						
		
						});
		
					}
				});*/
			});
		}
	});
	




//  ==================  商品  新增   =============================	
	$("#addNumberbox").numberbox({
		precision:2 // 小数点后的显示精度（2位）
	});
	$("#addBtn").click(function(){
		$("#addProductDialog").dialog("open");
	});
	
	$("#addProductDialog").dialog({
		buttons:[
		   {text:"保存", handler: function(){				   
			   $("#addProductForm").form("submit", {
				   url:"${root}/admin/product/save",
				   onSubmit: function(){
					   return $("#addProductForm").form("validate");
				   },
				   success: function(){
					   $("#addProductDialog").dialog("close");
					   $("#productTable").datagrid("reload");
				   }
			   });
		   }}
		]
	});


	$("#addUpload").euploadify({
 		width: 580,
        //height: 400,
        multi: true,
        multiTemplate: 'simple',
        auto: false,
        required: true,
        removeCompleted: true,// 移除已经上传的图片
        swf: '${root}/easyui/plugins/uploadify/uploadify.swf',
        uploader: '${root}/upload',
        onUploadSuccess: function(file, data){
        	var $addImages = $("#addImages");
        	// uploadify 返回的是json字符串，需要手动转换为json对象
        	var json = JSON.parse(data);
        	var md5 = json.filename.replace(/\..*/,"");
        	// 动态生成图片对应的文本框，文本框中包含图片名
        	// 生成图片预览，生成image标签
        	if($("img[src*="+md5+"]").length == 0) {
        		var html = "<div class='row'><img src='${root}/image/"+json.filename+"'/><input type='hidden' name='images' value='"+json.filename+"'/><span>移除("+file.name+")</span></div>";
        		$addImages.append($(html));
        	}	        	
        }
 	});
	
	$("#addImages").on("click", "span", function(){
		$(this).parent().remove();
	});

/* 	//  ==================  商品 修改   =============================
	$("#updateNumberbox").numberbox({
		precision:2
	});
	$("#updateBtn").click(function(){
		var row = $("#productTable").datagrid('getSelected');
		console.log(row);
		if(row){
			$("#updateProductForm").form("load", {id:row.id,name:row.name,price:row.price,weight:row.weight,onsale:row.onsale,onsaleDate:row.onsaleDate,store:row.store,detail:row.detail,category_id:row.category_id});
			$("#updateProductDialog").dialog("open",function(){
				buttons:[
					{ text:"保存",handler:function(){
						$("updateProductForm").form("submit",{
							url:"",
							onsubmit: function(){
								return $("#updateProductForm").form(validate);
							},
							success: function(){
								$("#updateProductDialog").dialog("close");
								$("#productTable").datagrid("reload");
							}
						
						});
						}
					}
				]
			});
		}else{
			$.messager.alert("请选择要修改的行");
			return;
		}
	});
 */
	
//  ==================  商品 列表   =============================	
	$("#productTable").datagrid({
		url:"${root}/admin/product/findByPage",
		fitColumns:true,
		fit: true,
		pagination: true,
		singleSelect: true,
		toolbar: "#productToolbar",
		pageSize: 5,
		pageList: [5,10,15,20],
		columns:[[
		    {title:"编号", field:"id", width: 100},
		    {title:"名称", field:"name", width: 300},
		    {title:"价格", field:"price", width: 100, sortable:true},
		    {title:"重量", field:"weight", width: 100},
		    {title:"上架", field:"onsale", width: 100},
		    {title:"上架日期", field:"onsaleDate", width: 100, sortable:true},
		    {title:"库存", field:"store",width:100},
		    {title:"详情页面", field:"detail", width: 100},
		    {title:"类别编号", field:"category_id", width: 100}
		]]
	});

//  ==================  类别 级别判断   =============================
	function getLevel(id) {
		if(id / 100 % 100 > 0) {
			return 3;
		} else if(id / 10000 % 100 > 0) {
			return 2;
		} else {
			return 1;
		}
	}
	
	
	
	
	
	//　商品  新增时的combotree
	$("#categoryCombo").combotree({
		url:"${root}/admin/attr/findAll",
		dataPlain: true,
		textField: "text",
		valueField: "id",
		onSelect: function(record){
			if(getLevel(record.id) != 3){
				$("#categoryCombo").combotree("clear");
				$.messager.alert("只能为3级类别添加商品");
				return;
			}
			$.get("${root}/admin/attr/findByCategoryFetch", {cid:record.id}, function(json){
				//console.log(json);
				var $attrs = $("#attrs").empty();
				for(var i = 0; i < json.rows.length; i++) {
					var html = "<tr><td>"+json.rows[i].name+"</td><td><input type='hidden' name='attr_names' value='"+json.rows[i].name+"'/><input type='text' class='attrCombo' name='values'></td></tr>";
					$(html).appendTo($attrs);
				}
				var combos = $attrs.find(".attrCombo");
				for(var i = 0; i < json.rows.length; i++) {
					$(combos[i]).combobox({
						textField: "name",
						valueField: "name",
						required: true,
						data: json.rows[i].attrValues
					});
				}					
			});
		}
	});
	
		
</script>
</body>
</html>